﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace Model
{
    public class Server
    {
        private bool running;
        private int port;

        IPEndPoint klientport; // attribut til at gemme klient port.
        Socket serverLytter; // Komunikations kontakt hvor serveren kan lytte på. 
        Socket klientSocket;
        Thread klientHandlerTråd;
        Auktion auktion;

        private bool stopRequested;

        //public delegate void SendHilsen(string sender);


        /**** Kontroller *****/
        public Server(int port, Auktion auktion)
        {
            this.port = port;
            this.auktion = auktion;
            this.running = true;
            this.serverLytter = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            this.klientport = new IPEndPoint(IPAddress.Any, port);
            serverLytter.Bind(klientport);
            serverLytter.Listen(10);
        }


        public void Start()
        {
            while (running)
            {
                try
                {
                    klientSocket = serverLytter.Accept();
                    Klienthandler klientHandler = new Klienthandler(klientSocket, auktion);
                    klientHandlerTråd = new Thread(klientHandler.Start);
                    klientHandlerTråd.Start();
                }
                catch (SocketException)
                {

                }

                catch (Exception e)
                {
                    Console.WriteLine(e);
                }

            }

            serverLytter.Shutdown(SocketShutdown.Both);
        }


        public bool StopRequested
        {
            get { return stopRequested; }
            set { stopRequested = value; }
        }

        public void StopServer()
        {
            stopRequested = false;
        }
    }
}
